//
//  NSArray+Extension.m
//  Tools
//
//  Created by xlz on 2018/5/12.
//  Copyright © 2018年 com.365hy. All rights reserved.
//

#import "NSArray+Extension.h"

@implementation NSArray (Extension)

#pragma mark - 数组 转 json字符串
- (NSString *)wd_toJsonString {
    if ([NSJSONSerialization isValidJSONObject:self]) {
        NSError *error = nil;
        // 1.转化为 JSON 格式的 NSData
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
        if (error) {
            NSLog(@"数组转JSON字符串失败：%@", error);
        }
        // 2.转化为 JSON 格式的 NSString
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return nil;
}

#pragma mark - 数组倒序
- (NSArray *)wd_reverse {
    return [[self reverseObjectEnumerator] allObjects];
}

@end

@implementation NSMutableArray (Extension)
#pragma mark - 添加元素
- (void)wd_addObject:(id)anObject {
    if (wd_isEmpty(anObject)) {
        return;
    }
    [self addObject:anObject];
}

/** 判断对象是否为空 */
static inline BOOL wd_isEmpty(id thing) {
    return thing == nil ||
    [thing isEqual:[NSNull null]] ||
    [thing isEqual:@"null"] ||
    [thing isEqual:@"(null)"] ||
    ([thing respondsToSelector:@selector(length)]
     && [(NSData *)thing length] == 0) ||
    ([thing respondsToSelector:@selector(count)]
     && [(NSArray *)thing count] == 0);
}

@end
